use yew::prelude::*;
use yew_router::prelude::*;

use crate::{
  components::{crate_form::CrateForm, header::Header},
  contexts::CurrentUserContext,
  hooks::{use_crate, use_rustaceans},
  pages::slidebar::Slidebar,
  Route,
};

#[derive(Properties, PartialEq)]
pub struct Props {
  pub crates_id: i32,
}

#[function_component]
pub fn CratesEdit(props: &Props) -> Html {
  let current_user_ctx = use_context::<CurrentUserContext>()
    .expect("Current user context is missing");

  match &current_user_ctx.token {
    Some(token) => {
      let loading = html! { <p>{"loading..."}</p> };

      html! {
        <>
        <Header/>
        <Slidebar/>
        <div>
          <Suspense fallback={loading}>
            <CratesEditForm crates_id={props.crates_id} token={token.clone()}/>
          </Suspense>
        </div>
      </>
      }
    }
    None => html! {
      <Redirect<Route> to={Route::Login}/>
    },
  }
}

#[derive(Properties, PartialEq)]
struct CratesEditFormProps {
  pub crates_id: i32,
  pub token: AttrValue,
}

#[function_component]
fn CratesEditForm(props: &CratesEditFormProps) -> HtmlResult {
  let a_crate = use_crate(props.token.as_ref(), props.crates_id)?;
  let rustaceans = use_rustaceans(&props.token.clone())?;
  Ok(html! {
    <CrateForm a_crate={a_crate} authors={rustaceans}/>
  })
}
